/*
 * complex.cpp
 *
 *  Created on: Sep 16, 2013
 *      Author: andrewts
 */

#include <iostream>
#include <stdlib.h>
#include "complex.h"

Complex::Complex()
{
	real = 0;
	imag = 0;
}

Complex::Complex(double r)
{
	real = r;
	imag = 0;
}

Complex::Complex(double r, double i)
{
	real = r;
	imag = i;
}

Complex::Complex(const Complex &z)
{
	real = z.real;
	imag = z.imag;
}

Complex Complex::operator +(Complex a)
{
	return Complex(real + a.real, imag + a.imag);
}

Complex Complex::operator -(Complex a)
{
	return Complex(real - a.real, imag - a.imag);
}

Complex Complex::operator *(Complex a)
{
	return Complex(real * a.real - imag * a.imag,
			real * a.imag + imag * a.real);
}

Complex Complex::operator /(Complex a)
{
	double t = a.real * a.real + a.imag * a.imag;
	return Complex(real * a.real / t + imag * a.imag / t,
			imag * a.real / t - real * a.imag / t);
}

void Complex::operator +=(Complex a)
{
	real += a.real;
	imag += a.imag;
}

Complex& Complex::operator -=(Complex a)
{
	real -= a.real;
	imag -= a.imag;
	return *this;
}

Complex& Complex::operator *=(Complex a)
{
	real = real * a.real - imag * a.imag;
	imag = real * a.imag + imag * a.real;
	return *this;
}

Complex& Complex::operator /=(Complex a)
{
	Complex res(*this);
	res = res / a;
	*this = res;
	return *this;
}

Complex& Complex::operator =(const Complex &a)
{
	real = a.real;
	imag = a.imag;
	return *this;
}

std::ostream & operator <<(std::ostream &os, Complex z)
{
	os << "(" << z.real << " " << (z.imag < 0 ? '-' : '+') << " " << (z.imag > 0 ? z.imag : -z.imag) << "i)";
	return os;
}

int test_class_Complex(void)
{
	Complex x(3, 1);
	std::cout << "x = " << x << std::endl;

	Complex y(2);
	std::cout << "y = " << y << std::endl;
	x = Complex(11, 12);
	std::cout << "x + y = " << x + y << "; x - y = " << x - y << std::endl << std::endl;

	x = Complex(2, 3);
	y = Complex(1, 2);
	std::cout << "x = " << x << std::endl;
	std::cout << "y = " << y << std::endl;
	std::cout << "-1 * x = " << x * -1 << std::endl;
	std::cout << "x + y = " << x + y << std::endl;
	std::cout << "x - y = " << x - y << std::endl;
	std::cout << "x * y = " << x * y << std::endl;
	std::cout << "(3 + 2i) * (3 - 2i) = " << Complex(3, 2) * Complex(3, -2) << std::endl;
	std::cout << "x / y = " << x / y << std::endl;
	x -= y;
	std::cout << "x -= y : x = " << x << std::endl;
	x += y;
	std::cout << "x += y : x = " << x << std::endl;
	x += y * 2;
	std::cout << "x += y * 2 : x = " << x << std::endl;
	x /= y;
	std::cout << "x /= y : x = " << x << std::endl;

	return 0;
}
